﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tcp.Performance.Toolkit.HubServer.Concurrent_Collection
{
    public class HubGuiCollection<T>
    {

        private readonly BlockingCollection<T> _queue;
        readonly Stopwatch _stopWatch = new Stopwatch();

        public delegate void OnRead(T model);

        OnRead _onReadDelegate;

        public OnRead OnReadDelegate
        {
            get { return _onReadDelegate; }
            set { _onReadDelegate = value; }
        }

       

        

        public HubGuiCollection()
        {
            _queue = new BlockingCollection<T>(); //will create queue by default
            Task.Factory.StartNew(ReadAndProcess);
       

        }

        private void ReadAndProcess()
        {
            _stopWatch.Start();
            foreach (var element in _queue.GetConsumingEnumerable())
            {
                if (_onReadDelegate != null)
                    _onReadDelegate.Invoke(element);
             
            }


            _stopWatch.Reset();
        }

        public void Write(T elementToBeadded)
        {
            _queue.TryAdd(elementToBeadded);
        }




    }
}
